package mod_rewrite

import (
	"ezcloud/gw/internal/define"
	"ezcloud/gw/pkg/route"
	"regexp"
)

/*
RewritePath.Regexp = /[0-9A-Za-z_.]+/(?P<endfix>.*)
RewritePath.Replace = '/${endfix}'
*/
func ModRewritePath(context *route.RouteContext, chain route.RouteFilterChain) {
	// regexp  := `/[0-9A-Za-z_.]+/(?P<segment>.*)`
	// replace := "/${segment}"
	curRoute := context.Get(route.X_ROUTE).(*define.RouteDefine)
	filterDefines := context.Get(route.X_FILTER_DEFINES).(map[string]*define.FilterDefine)

	if curRoute != nil && filterDefines != nil {

		filterDefine := filterDefines["RewritePath"]
		if filterDefine != nil {

			r := filterDefine.Get("Regexp")
			p := filterDefine.Get("Replace")

			if exp, ok := r.(*regexp.Regexp); ok {
				if exp.MatchString(context.RequestUri) {
					newRequestUri := exp.ReplaceAll([]byte(context.RequestUri), p.([]byte))
					context.RequestUri = string(newRequestUri)
				}
			}
		}
	}

	chain.Filter(context)
}
